import React, {Component} from 'react';
import {getChatContentList, getOnlineUserList} from "../../api/chat";
import localStorage from "../../helper/ls";

class Chat extends Component {

  constructor(props) {
    super(props);
    this.state = {
      sendValue: '',
      userList: [],
      receiveUser: null,
      user: null,
      chatContentList: []
    };
  }

  async componentDidMount() {
    const result = await getOnlineUserList();
    const user = localStorage.get('user');
    let userList = result.filter(u => u._id !== user._id);
    let receiveUser = null;
    if (userList.length > 0) {
      receiveUser = userList[0];
      receiveUser.active = true;
      this.handleGetChatContentList({
        sendId: user._id,
        receiveId: receiveUser._id,
      });
    }
    this.setState({userList, user, receiveUser: receiveUser});
    const {socket} = this.props;
    socket.emit('recordId', {userId: user._id});
    socket.on('receiveMessage', chat => {
      const chatContentList = this.state.chatContentList;
      this.setState({chatContentList: chatContentList.concat(chat)});
    });
  }

  abstractSendMessage = (data) => {
    const {socket} = this.props;
    console.log('socket', socket);
    try {
      socket.emit('sendMessage', data);
    } catch (err) {
      console.log(err);
    }
  };

  handleSendValueChange = (e) => {
    this.setState({
      sendValue: e.target.value
    });
  };

  handleSendMessage = () => {
    console.log('开始发送信息...');
    const {sendValue, user, receiveUser} = this.state;
    if (!receiveUser) {
      return;
    }
    if (!sendValue.trim()) {
      return;
    }
    this.abstractSendMessage(JSON.stringify({
      sendId: user._id,
      receiveId: receiveUser._id,
      content: sendValue.trim()
    }));
    this.setState({sendValue: ''});
  };

  handleUserLogout = () => {
    this.props.handleUserLogout();
  };

  handleSelectUser = (receiveUser) => {
    const {userList, user} = this.state;
    userList.map(u => {
      if (receiveUser && u._id === receiveUser._id) {
        u.active = true;
      } else {
        u.active = false;
      }
      return u;
    });
    this.setState({userList, receiveUser});
    if (receiveUser) {
      this.handleGetChatContentList({
        sendId: user._id,
        receiveId: receiveUser._id,
      });
    }
  };

  processUserClassName = user => {
    if (user.active) {
      return "pointer active";
    }
    return "pointer";
  };

  handleGetChatContentList = async (params) => {
    try {
      const result = await getChatContentList(params);
      this.setState({chatContentList: result});
    } catch (err) {
      console.log(err);
    }
  };

  processChatContentClassName = item => {
    if (item.sendId === this.state.user._id) {
      return 'chat-item send';
    }
    return 'chat-item receive';
  };

  renderChatContent = () => {
    const {user, receiveUser} = this.state;
    return (
      <div className="chat-wrapper">
        <ul className="chat-list">
          {
            this.state.chatContentList.length > 0 ?
              this.state.chatContentList.map(item => (
                  <li
                    className={this.processChatContentClassName(item)}
                    key={item._id}>
                    {
                      item.sendId === receiveUser._id ?
                        <span className="name">{receiveUser.username}:</span> :
                        null
                    }
                    <span className="content">{item.content}</span>
                    {
                      item.sendId === user._id ?
                        <span className="name">:{user.username}</span> :
                        null
                    }
                  </li>
                )
              ) :
              <p className="bold">没有聊天记录</p>
          }
        </ul>

        <ul className="user-list">
          {
            this.state.userList.map((user, index) => (
              <li onClick={() => this.handleSelectUser(user, index)}
                  className={this.processUserClassName(user)}
                  key={user._id}
              >{index + 1}. {user.username}</li>
            ))
          }
        </ul>
      </div>
    );
  };

  render() {
    const {sendValue, user} = this.state;
    return (
      <div className="main">
        <div className="header">
          <p className="flex-between">
            <span className="user">{user && <span className="bold">当前用户: {user.username}</span>}</span>
            <button onClick={this.handleUserLogout}>退出</button>
          </p>
        </div>
        {this.renderChatContent()}
        <div className="footer">
          <input type="text"
                 value={sendValue}
                 placeholder="请输入"
                 onChange={this.handleSendValueChange}
          />
          <button onClick={this.handleSendMessage}>发送信息</button>
        </div>
      </div>
    );
  }
}

export default Chat;
